<?php

namespace App\Models\templates;

use App\Models\Model;

/**
 * 配送模板模型
 * Class Delivery
 *
 * @package app\common\model
 * @property int $id 模板id
 * @property string $name 模板名称
 * @property mixed $method 计费方式(10按件数 20按重量)
 * @property int $sort 排序方式(数字越小越靠前)
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\templates\DeliveryRule[] $rule
 * @property-read int|null $rule_count
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery whereMethod($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\templates\Delivery whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Delivery extends Model
{

    protected $fillable = [
        'name',
        'method',
        'sort',
    ];

    /**
     * 添加新记录
     * @param $data
     * @return bool|int
     */
    public function add($data)
    {
        if (!isset($data['rule']) || empty($data['rule'])) {
            $this->error = '请选择可配送区域';
            return false;
        }

        if ($model = $this->create($data)) {
            return $model->createDeliveryRule($data['rule'],$model->id);
        }
        return false;
    }


    /**
     * 添加模板区域及运费
     * @param $data
     * @return int
     */
    private function createDeliveryRule($data,$id)
    {
        $save = [];
        $connt = count($data['region']);
        for ($i = 0; $i < $connt; $i++) {
            $save[] = [
                'region' => $data['region'][$i],
                'first' => $data['first'][$i],
                'first_fee' => $data['first_fee'][$i],
                'additional' => $data['additional'][$i],
                'additional_fee' => $data['additional_fee'][$i],
                'delivery_id' => $id
            ];
        }
        $this->rule()->delete();
        return $this->rule()->insert($save);
    }

    /**
     * 关联配送模板区域及运费
     */
    public function rule()
    {
        return $this->hasMany(DeliveryRule::class);
    }

    /**
     * 计费方式
     * @param $value
     * @return mixed
     */
    public function getMethodAttribute($value)
    {
        $method = [10 => '按件数', 20 => '按重量'];
        return ['text' => $method[$value], 'value' => $value];
    }

    /**
     * 获取全部
     * @return mixed
     */
    public static function getAll()
    {
        $model = new static;
        return $model->order(['sort' => 'asc'])->select();
    }

    /**
     * 获取列表
     */
    public function getList()
    {
        return $this->with(['rule'])
            ->order(['sort' => 'asc'])
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
    }

    /**
     * 运费模板详情
     * @param $delivery_id
     */
    public static function detail($delivery_id)
    {
        return self::with('rule')->find($delivery_id);
    }

    /**
     * 编辑记录
     * @param $data
     * @return bool|int
     */
    public function edit($data) {
        if (!isset($data['rule']) || empty($data['rule'])) {
            $this->error = '请选择可配送区域';
            return false;
        }
        if ($data['method']){
            $this->method = $data['method'];
        }
        if ($this->save($data)) {
            return $this->createDeliveryRule($data['rule'],$this->id);
        }
        return false;
    }

    /**
     * 验证用户收货地址是否存在运费规则中
     * @param $city_id
     * @return bool
     */
    public function checkAddress($city_id)
    {
        $cityIds = explode(',', implode(',', array_column($this->rule->toArray(), 'region')));
        return in_array($city_id, $cityIds);
    }


    /**
     * 计算配送费用
     * @param $total_num
     * @param $total_weight
     * @param $city_id
     * @return float|int|mixed
     */
    public function calcTotalFee($total_num, $total_weight, $city_id)
    {
        $rule = [];  // 当前规则
        foreach ($this->rule as $item) {
            if (in_array($city_id, $item->region_data)) {
                $rule = $item;
                break;
            }
        }

        // 商品总数量or总重量
        $total = $this->method['value'] == 10 ? $total_num : $total_weight;

        if ($total <= $rule->first) {
            return number_format($rule->first_fee, 2);
        }
        // 续件or续重 数量
        $additional = $total - $rule->first;
        if ($additional <= $rule->additional) {

            return number_format($rule->first_fee + $rule->additional_fee, 2);
        }

        // 计算续重/件金额
        if ($rule->additional < 1) {
            // 配送规则中续件为0
            $additionalFee = 0.00;
        } else {
            $additionalFee = bcdiv($rule->additional_fee, $rule->additional, 2) * $additional;
        }
        return number_format($rule->first_fee + $additionalFee, 2);
    }


}
